/*
 * =====================================================================================
 *
 *       Filename:  main.cc
 *
 *    Description:
 *
 *        Version:  1.0
 *        Created:  2022年01月21日 11时24分06秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  first_name last_name (fl), fl@my-company.com
 *        Company:  my-company
 *
 * =====================================================================================
 */

#include <iostream>
#include <pthread.h>

using namespace std;

static long long total = 0;

pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;

void* func(void*) {
    long long i;

    for (i = 0; i < 100000000LL; i++) {
        pthread_mutex_lock(&m);
        total += i;
        cout << "total: " << total << endl;
        pthread_mutex_unlock(&m);
    }
}

int main() {
    pthread_t thread1, thread2;

    if (pthread_create(&thread1, NULL, &func, NULL)) {
        throw;
    }

    if (pthread_create(&thread2, NULL, &func, NULL)) {
        throw;
    }

    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    cout << "total: " << total << endl;
}
